const mongoose = require('../connect')
const Schema = mongoose.Schema

const SeatCounterSchema = mongoose.Schema({
  _id: { type: String },
  seq: { type: Number, default: 0 }
})

const SeatCounter = mongoose.model('SeatCounter', SeatCounterSchema)

const SeatSchema = mongoose.Schema({
  _id: {type: String},
  innei_number: {type: String},
  category_id: {
    type: String,
    ref: 'category'
  },
  meta: {
    createdAt: {
      type: Date,
      dafault: Date.now()
    },
    updatedAt: {
      type: Date,
      dafault: Date.now()
    }
  }
});

SeatSchema.pre('save', function (next) {
  let doc = this;
  SeatCounter.findByIdAndUpdate({ _id: 'seatId' }, { $inc: { seq: 1 } }, { new: true, upsert: true }, function (error, counter) {
      if (error)
          return next(error);
      doc._id = counter.seq;
      if (doc.isNew){
        doc.meta.createdAt = doc.meta.updatedAt = Date.now()
      }else {
        doc.meta.updatedAt = Date.now()
      }
      next()
  });
})



const Seat = mongoose.model('Seat', SeatSchema)

module.exports = Seat